<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <!--  标题行    -->
            <el-row :gutter="20" style="margin: 0px -50px 20px 5px;">
                <el-col :span="21"><h1 class="my-heading">上传资料</h1></el-col>
                <el-col :span="1.5"><el-button @click="uploadSysFileSubmit">保存</el-button></el-col>
                <el-col :span="1.5"><el-button @click="goBack">返回</el-button></el-col>
            </el-row>
            <!--    条件行   -->
            <el-row v-show="showSearch">
                <el-form :model="queryForm" :rules="queryFormRules" ref="queryRef" label-width="80px" :inline="true" @keyup.enter="getDataList">
                    <el-form-item label="参与组织" prop="studyGroupId">
                        <el-tree-select
                                v-model="queryForm.studyGroupId"
                                :data="options1"
                                :props="{ value: 'id', label: 'name', children: 'children' }"
                                @current-change="treeHandleChange"
                                clearable
                                check-strictly
                                :render-after-expand="false"
                                placeholder="请选择"/>
                    </el-form-item>
                    <el-form-item label="参与岗位" prop="studyPostIds">
                        <el-select  @change="getItem1" v-model="queryForm.studyPostIds" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="请选择" style="width: 240px">
                            <el-option v-for="item in postList" :key="item.postId" :label="item.postName" :value="item.postId"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="专业名称" prop="majorNameId">
                        <el-select @change="getItem3" v-model="queryForm.majorNameId" filterable :required="true">
                            <el-option v-for="item in options2"  :key="item.zymcId" :label="item.zymcName" :value="item.zymcId"/>
                        </el-select>
                    </el-form-item>
                    <el-icon style="font-size: 1.6rem;font-weight: bold;margin-left: 5px"><Plus :visible.sync="centerDialogVisible" @click="centerDialogVisible=true"/></el-icon>
                    <!--                <el-form-item label="专业等级" prop="dataLevelId" style="margin-left: 15px">-->
                    <!--                    <el-select v-model="queryForm.dataLevelId" filterable  style="width: 240px" >-->
                    <!--                        <el-option v-for="item in zydjnamelist"  :key="item.zydjId" :label="item.zydjName" :value="item.zydjId"/>-->
                    <!--                    </el-select>-->
                    <!--                </el-form-item>-->
                    <el-form-item label="关键点" prop="keyPointIds" style="margin-right: 170px">
                        <el-select @change="getItem2" v-model="queryForm.keyPointIds" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" placeholder="请选择" style="width: 240px">
                            <el-option v-for="item in keypointsListData" :key="item.keyId" :label="item.keyPoint" :value="item.keyId"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="资料简介" prop="remark" style="width: 320px">
                        <el-input v-model="state.queryForm.remark" :rows="3" type="textarea" placeholder="Please input"/>
                    </el-form-item>
                </el-form>
            </el-row>


            <!--   表格   -->
            <el-table :data="dataList" v-loading="loading" border
                      :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                      @selection-change="selectionChangHandle"
                      @sort-change="sortChangeHandle">
                <el-table-column type="selection" width="40" align="center" />
                <el-table-column prop="dataFileId" label="#" width="50" />
                <el-table-column prop="fileName" label="上传文件名称"  show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="fileNameView" label="资料名称"  show-overflow-tooltip>
                    <template #default="scope">
                        <input type="text" v-model="scope.row.fileNameView" class="ipt" style="width:200px;text-align: center;" />
                    </template>
                </el-table-column>
                <el-table-column  width="120" prop="fileSize" label="文件大小"  show-overflow-tooltip/>
                <el-table-column width="200" prop="minTime" label="最低学习时长"  show-overflow-tooltip>
                    <template #default="scope">
                        <input type="text" v-model="scope.row.minTime" class="ipt" style="width:100px;text-align: center;" />
                    </template>
                </el-table-column>
                <el-table-column width="200" prop="timeOut" label="超时提醒时长"  show-overflow-tooltip>
                    <template #default="scope">
                        <input type="text" v-model="scope.row.timeOut" class="ipt" style="width:100px;text-align: center;" />
                    </template>
                </el-table-column>
                <el-table-column prop="fileNameView" label="资料简介"  show-overflow-tooltip>
                    <template #default="scope">
                        <input type="text" v-model="scope.row.remark" class="ipt" style="width:100px;text-align: center;" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="400">
                    <template #default="scope">
<!--                        <el-button type="primary" @click="preview(scope.row)">-->
<!--                            <el-link :href="scope.row.fileAddress"  :underline="false" target="_blank" style="color: #fff">预览</el-link>-->
<!--                        </el-button>-->
                        <el-button icon="RefreshLeft" text type="primary" v-auth="'train_kszlFile_edit'"
                                   @click="changeHandle(scope.row)">更新</el-button>
                        <el-button icon="edit-pen" text type="primary" v-auth="'train_kszlFile_edit'"
                                   @click="formDialogRef.openDialog(scope.row.id)">编辑内容</el-button>
                        <el-button icon="delete" text type="primary" v-auth="'train_kszlFile_del'" @click="handleDelete([scope.row.id])">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 创建试题、编辑  -->
        <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
        <!-- 新增专业名称、专业等级、关键点  -->
        <el-dialog v-model="centerDialogVisible" title="新增" @close="clean" width="30%">
            <el-form :model="keypointsform"  :rules="keypointsRules" ref="pointsformlist">
                <el-form-item label="专业名称"   prop="zymcName"  >
                    <el-select @change="getProfessionalGrade" v-model="keypointsform.zymcName" filterable allow-create default-first-option :reserve-keyword="false" style="width: 240px">
                        <el-option v-for="item in options2"  :key="item.zymcId" :label="item.zymcName" :value="item.zymcName"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="专业等级"  prop="zydjName">
                    <el-select @change="getProfessionalGrade1" v-model="keypointsform.zydjName" filterable allow-create default-first-option :reserve-keyword="false" style="width: 240px">
                        <el-option v-for="item in zydjnamelist"  :key="item.zydjId" :label="item.zydjName" :value="item.zydjName"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="关键点"  prop="keyPoint">
                    <el-input v-model="keypointsform.keyPoint" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="备注"  prop="remark">
                    <el-input v-model="keypointsform.remark" type="textarea"/>
                </el-form-item>
            </el-form>
            <template #footer>
  <span class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取消</el-button>
    <el-button type="primary" :visible.sync="centerDialogVisible" @click="onSubmit1">提交</el-button>
  </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="systemKszlFile1">
    //导入
    import { BasicTableProps, useTable } from "/@/hooks/table";
    import { useMessage, useMessageBox } from "/@/hooks/message";
    import { useDict } from '/@/hooks/dict';
    import { useRouter,useRoute } from 'vue-router';
    import { Session } from '/@/utils/storage';
    import type { UploadProps, UploadUserFile } from 'element-plus'
    import {ref} from "vue";
    import mittBus from '/@/utils/mitt';
    import { fetchList, delObjs, putObj, getObj,uploadSysFile, uploadSysFileData, fileSubmit } from "/@/api/train/kszlFile";
    import {keypointsList} from "/@/api/train/jnglKeyPoints";
    import {deptTree, syspost} from "/@/api/train/kszlData";
    import {getLevel, professionalnameList} from "/@/api/train/jnglProfessionLevel";
    import {saveProfession} from "/@/api/train/kszlFile";
    import {getEditList} from "/@/api/train/kszlData";

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    //新增
    const pointsformlist = ref();
    const loading = ref(false);
    // 定义变量内容
    const formDialogRef = ref()
    // 搜索变量
    const queryRef = ref()
    const showSearch = ref(true)
    // 多选变量
    const selectObjs = ref([]) as any
    const multiple = ref(true)
    //弹框显示
    const dialogVisible = ref(false)
    const centerDialogVisible = ref(false)
    const state: BasicTableProps = reactive<BasicTableProps>({
        queryForm: {}
    })
    // 表单元素
    const dom = ref()
    const studyGroup = ref()
    // 校验规则
    const rules = ref({
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
    })
    const keypointsRules = ref({
        zymcName: [{ required: true, message: '请输入专业名称',trigger: 'change'}],
        zydjName: [{ required: true, message: '请输入专业等级',trigger: 'change'}],
        keyPoint: [{ required: true, message: '请输入关键点',trigger: 'change'}],
    })
    const queryFormRules = ref({
        studyGroupId: [{ required: true, message: '请输入参与组织',trigger: 'change'}],
        studyPostIds: [{ required: true, message: '请输入参与岗位',trigger: 'change'}],
        majorNameId: [{ required: true, message: '请输入专业名称',trigger: 'change'}],
        keyPointIds: [{ required: true, message: '请输入关键点',trigger: 'change'}]
    })
    // 绑定数据
    const form = reactive({
        name: '',
        textarea:''
    })
    //新增弹框表单
    let keypointsform = reactive({
        keyId: "",
        zymcId: "",
        zydjId: "",
        keyPoint: "",
        remark: "",
        zymcName: "",
        zydjName: ""
    })
    //  table hook
    const {
        getDataList,
        sortChangeHandle,
        downBlobFile,
        tableStyle
    } = useTable(state)
    //返回上一页
    const router = useRouter();
    const route = useRoute();
    const goBack = () => {
        // router.go(-1);
        router.push('/train/kszlData/index');
    };
    //学习组织数据
    const options1 = ref<any[]>([]);
    //专业名称数据
    const options2 =reactive([{}])
    //表格数据
    const dataList =reactive([{}])
    const queryForm =reactive({})
    //文件ids
    const fileIds =reactive([])
    //fileTableList
    const fileTableList = reactive([{}])
    //专业等级
    const zydjnamelist = reactive([{}])
    //学习岗位
    const postList =reactive([{}])
    //关键点
    const keypointsListData = reactive([{}])
    //部门主键
    const pkDept = ref()
    //挂载完毕
    onMounted(()=>{
        console.log(route.query.sendId) // 输出 "value1"
            const id = route.query.sendId
            const params = `dataFileId=${id}`;
            console.log('params----',params)
            dataList.length = 0
            getEditList(params).then((res)=>{
                Object.assign(dataList, res.data.data)
                queryForm.studyGroup = dataList[0].studyGroupId
                // queryForm.studyPostIds= dataList[0].studyPostId
                queryForm.majorNameId= dataList[0].majorNameId
                // queryForm.keyPointIds= dataList[0].keyPointId
                queryForm.remark= dataList[0].remark
                // Object.assign(queryForm,dataList)
                console.log('dataList',dataList)
            })
        deptTreeList()
        getProfessionalName()
        getKeypointsList()
    })
    // 重置新增关键点form表单
    const clean = () => {
        pointsformlist.value.resetFields();
    }
    const getItem1=(val:any) =>{
        console.log(val,'2222222')
        let names = []
        postList.forEach(item => {
            for (let i = 0; i < val.length; i++) {
                if (item.postId == val[i]) {
                    names.push(item.postName)
                }
            }
        })
        state.queryForm.studyPosts = names
    }
    const getItem2=(val:any) =>{
        console.log(val,'33333')
        let names = []
        keypointsListData.forEach(item => {
            for (let i = 0; i < val.length; i++) {
                if (item.keyId == val[i]) {
                    names.push(item.keyPoint)
                }
            }
        })
        state.queryForm.keyPoints = names
    }
    const getItem3=(val:any) =>{
        console.log(val,'11111')
        options2.forEach(item => {
            if (item.zymcId == val) {
                state.queryForm.majorName = item.zymcName
            }
        })

    }
    // 参与组织
    const deptTreeList = () => {
        deptTree().then((res) => {
            options1.value = res.data;
            // console.log('111、、、',options1.value)
        });
    };
    //专业名称
    const  getProfessionalName = () => {
        professionalnameList().then((res) => {
            Object.assign(options2, res.data)
            // console.log("专业名称",options2);
        });
    };

    //专业等级
    const getProfessionalGrade = (val:any) => {
        // console.log(keypointsform.zymcName,val,"zymcId");
        let zide = '';
        options2.forEach(item => {
            if (item.zymcName == val) {
                zide = item.zymcId
                keypointsform.zymcId = item.zymcId
                // console.log("zide",zide);
            }
        })
        if(zide){
            getLevel(zide).then((res) => {
                Object.assign(zydjnamelist, res.data)
                // console.log("专业等级",zydjnamelist);
            })
        }else {
            const list = {}
            Object.assign(zydjnamelist, list)
        }
    }
    const getProfessionalGrade1 = (val:any) => {
        // console.log(val,"zymcId");
        let zide = '';
        zydjnamelist.forEach(item => {
            if (item.zydjName == val) {
                zide = item.zydjId
                keypointsform.zydjId = item.zydjId
                // console.log("zide",zide);
            }
        })
    }
    //关键点
    const  getKeypointsList = () =>{
        keypointsList().then((res: any) => {
            Object.assign(keypointsListData, res.data.records)
            // console.log('keypointsListData----', keypointsListData)
        });
    }
    //上传资料保存
    const uploadSysFileSubmit =async () =>{
        const valid =await  queryRef.value.validate().catch(() => {});
        state.queryForm.state = "1"
        state.queryForm.studyGroupId = pkDept.value
        state.queryForm.studyGroup = studyGroup.value
        fileSubmit(state.queryForm).then((res) => {
            console.log('编辑上传资料保存',res)
        });
        // queryRef.value.resetFields();
        router.push('/train/kszlData/index');
    }
    // 新增关键点
    const onSubmit1 = async () => {
        // console.log('1------',keypointsform.zymcName)
        const valid = await pointsformlist.value.validate().catch(() => {});
        try {
            centerDialogVisible.value = true;
            await saveProfession(keypointsform);
            centerDialogVisible.value= false;
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            centerDialogVisible.value = false;
        }

    };
    //拿到树节点id
    const treeHandleChange = (value:any) => {
        // value为选中节点数据
        pkDept.value = value.id
        studyGroup.value = value.name
        // console.log(value,'00000')
        getPostList()
    }
    // watch(  () => keypointsform.zymcId, // 观察的值
    //     (newVal, oldVal) => {
    //         // 当 keypointsform.zymcId 发生变化时，执行以下操作
    //         console.log('zymcId 发生变化:', newVal, '旧值:', oldVal);
    //         // 在这里编写你的逻辑代码
    //     },
    //     { immediate: true } // 立即执行一次监听器，而不是等到值首次变化时才执行
    // );
    //学习岗位
    const getPostList =  () =>{
        const num = pkDept.value
        syspost(num).then((res: any) => {
            Object.assign(postList, res.data)
            // console.log('----',res.data)
        });
    }
    const fileList = ref<UploadUserFile[]>([])
    const newId = ref<string>();
    const file1 = ref('');
    const handleChange = async (file: File, fileList: any[]) => {
        console.log('file', file.raw)
        const uid = file.raw.uid
        fileIds.push(uid);
        console.log('uid-----',uid,fileIds)
        const formData = new FormData();
        formData.append('file', file.raw);
        try {
            const res = await uploadSysFile(formData);
            file1.value = res.data;
            console.log('file1.value,成功了',file1.value)
        } catch (err) {
            console.error(err,'报错了');
        }
        fileHide.value = fileList.length >= 1;
        const fileData = file1.value
        uploadSysFileData(fileData).then((res)=>{
            // console.log('res',res)
        })
    }
    const fileRemove = (file: File, fileList: any[]) => {
        console.log(file,fileList,'---------')
        fileHide.value = fileList.length >= 1;
        // file1.value = '';
    }
    const fileHide = ref(false);
    //修改表格单元格
    const changeHandle = (currentRow:any)=>{
        putObj(currentRow).then((res)=>{
            // console.log('--111',res)
        })
    }
    // 清空搜索条件
    const resetQuery = () => {
        // 清空搜索条件
        queryRef.value?.resetFields()
        // 清空多选
        selectObjs.value = []
        getDataList()
    }
    // 多选事件
    const selectionChangHandle = (objs: { id: string }[]) => {
        selectObjs.value = objs.map(({ id }) => id);
        multiple.value = !objs.length;
    };
    // 删除操作
    const handleDelete = async (ids: string[]) => {
        try {
            await useMessageBox().confirm('此操作将永久删除');
        } catch {
            return;
        }
        try {
            await delObjs(ids);
            getDataList();
            useMessage().success('删除成功');
        } catch (err: any) {
            useMessage().error(err.msg);
        }
    };
</script>
<style lang="scss" scoped>
    .my-heading {
        color: black;
        font-weight: bold;
        font-size: 26px;
        margin-bottom: 10px;
    }
    .el-form{
        margin-left: 15px;
    }
    .select1{
        width: 50px;
    }

</style>